package com.sd.repay.service.impl;

import com.sd.repay.common.Constants;
import com.sd.repay.common.Page;
import com.sd.repay.dao.BaseDao;
import com.sd.repay.pojo.Balance;
import com.sd.repay.pojo.ProfitDetail;
import com.sd.repay.service.ProfitDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author
 * @Description:
 * @date 2017年10月25日
 */
@Service
public class ProfitDetailServiceImpl implements ProfitDetailService {

    private static Logger log = LoggerFactory.getLogger(ProfitDetailServiceImpl.class);

    @Autowired
    private BaseDao baseDao;


    /**
     * 保存收益记录
     *
     * @param detail
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public int saveProfitDetail(ProfitDetail detail) throws Exception {

        String sql = " INSERT INTO t_profit_detail(profit_no,profit_mer_type,profit_mer_no,source_mer_type,source_mer_no,agent_no,service_type,service_order_no,trans_amount,trans_time," +
                " profit_amount,mer_fee_rate,mer_single_fee,agent_fee_rate,agent_single_fee,allow_income,income_status,create_time,remark) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        List<Object> params = new ArrayList<>();
        params.add(detail.getProfitNo());
        params.add(detail.getProfitMerType());
        params.add(detail.getProfitMerNo());
        params.add(detail.getSourceMerType());
        params.add(detail.getSourceMerNo());
        params.add(detail.getAgentNo());
        params.add(detail.getServiceType());
        params.add(detail.getServiceOrderNo());
        params.add(detail.getTransAmount());
        params.add(detail.getTransTime());
        params.add(detail.getProfitAmount());
        params.add(detail.getMerFeeRate());
        params.add(detail.getMerSingleFee());
        params.add(detail.getAgentFeeRate());
        params.add(detail.getAgentSingleFee());
        params.add(detail.getAllowIncome());
        params.add(detail.getIncomeStatus());
        params.add(new Date());
        params.add(detail.getRemark());
        return baseDao.execute(sql, params.toArray());
    }

    /**
     * 根据类型及业务订单号查询是否存在收益记录
     *
     * @param serviceType
     * @param serviceOrderNo
     * @return
     * @throws Exception
     */
    @Override
    public ProfitDetail getProfitDetailByProfitMerAndService(String profitMerType, String profitMerNo, String serviceType, String serviceOrderNo) throws Exception {

        String sql = " SELECT * FROM t_profit_detail WHERE profit_mer_type = ? AND profit_mer_no = ? AND service_type = ? AND service_order_no = ? ";
        return baseDao.findFirst(ProfitDetail.class, sql, new Object[]{profitMerType, profitMerNo, serviceType, serviceOrderNo});
    }

    /**
     * 修改收益入账状态
     *
     * @param profitNo
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public int updateIncomeStatus(String profitNo) throws Exception {

        String sql = " UPDATE t_profit_detail SET income_status = ?, income_time = ? WHERE profit_no = ? AND allow_income = ? AND income_status = ? ";
        return baseDao.execute(sql, new Object[]{Constants.INCOME_STATUS_SUCC, new Date(), profitNo, Constants.ALLOW_INCOME_NEED, Constants.INCOME_STATUS_FAIL});
    }

    /**
     * 获取商户总收益金额
     *
     * @param merType
     * @param merNo
     * @return
     * @throws Exception
     */
    @Override
    public String getTotalProfitAmountByMer(String merType, String merNo) throws Exception {

        String sql = " SELECT IFNULL(SUM(trans_amount), 0) AS transAmount FROM t_profit_detail WHERE profit_mer_type = ? AND profit_mer_no = ? ";
        ProfitDetail summaryDetail = baseDao.findFirst(ProfitDetail.class, sql, new Object[]{merType, merNo});
        return summaryDetail == null ? "" : String.valueOf(summaryDetail.getTransAmount());
    }

    /**
     * 获取商户可提现金额和冻结金额
     *
     * @param merType
     * @param merNo
     * @return currBalance：可提现金额（今日余额加历史余额）；freezeBalance：冻结金额
     * @throws Exception
     */
    @Override
    public Map<String, String> getMerTypeBalance(String merType, String merNo) throws Exception {

        String sql = " SELECT IFNULL(SUM(curr_balance + his_balance), 0) AS currBalance, IFNULL(SUM(freeze_balance), 0) AS freezeBalance FROM t_balance WHERE mer_type = ? AND mer_no = ? ";
        Balance balance = baseDao.findFirst(Balance.class, sql, new Object[]{merType, merNo});

        Map<String, String> resMap = new HashMap<>();
        resMap.put("totalCurrBalance", balance == null ? "" : String.valueOf(balance.getCurrBalance()));
        resMap.put("totalFreezeBalance", balance == null ? "" : String.valueOf(balance.getFreezeBalance()));
        return resMap;
    }

    /**
     * 获取商户所有收益明细
     *
     * @param merType
     * @param merNo
     * @throws Exception
     */
    @Override
    public List<ProfitDetail> getProfitDetailByMer(String merType, String merNo) throws Exception {

        String sql = " SELECT * FROM t_profit_detail WHERE profit_mer_type = ? AND profit_mer_no = ? ";
        return baseDao.findList(ProfitDetail.class, sql, new Object[]{merType, merNo});
    }

    @Override
    public Page<ProfitDetail> getProfitDetailPageByMer(String merType, String merNo, String startTime, String endTime, int pageNo, int pageSize) throws Exception {
        String sql = " SELECT * FROM t_profit_detail WHERE profit_mer_type = ? AND profit_mer_no = ?   " +
                " and create_time between ? and ?  ";
        return baseDao.queryPagination(ProfitDetail.class, pageNo, pageSize, sql, merType, merNo, startTime, endTime);
    }

    /**
     * 获取所有未入账的收益明细
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<ProfitDetail> getUnIncomeProfitDetail() throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date now = new Date();

        Calendar nowCal = Calendar.getInstance();
        nowCal.setTime(now);
        nowCal.add(Calendar.DAY_OF_YEAR, -30);
        String beginTime = sdf.format(nowCal.getTime()) + " 00:00:00";

        nowCal = Calendar.getInstance();
        nowCal.setTime(now);
        nowCal.add(Calendar.MINUTE, -5);
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = sdf.format(nowCal.getTime());

        String sql = " SELECT * FROM t_profit_detail WHERE allow_income = ? AND income_status = ? AND create_time >= ? AND create_time <= ? ";
        return baseDao.findList(ProfitDetail.class, sql, new Object[]{Constants.ALLOW_INCOME_NEED, Constants.INCOME_STATUS_FAIL, beginTime, endTime});
    }
}